//
//  StarView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 2. 3..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "StarView.h"

@implementation StarView
@synthesize itemArray, responseData, imageURL, starID, mTwitter;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        self.backgroundColor = ColorFromRGB(0x413c43);
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        itemArray = [[NSMutableArray alloc] init];
        
        [self makeObject];
    }
    return self;
}

-(void)makeObject{
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, mySize.width, 20)];
    bgView.backgroundColor = ColorFromRGB(0xe9e9e9);
    [self addSubview:bgView];
    
    
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self setSubTitleIcond:[UIImage imageNamed:@"icon_follower"] andTitle:nil]; //subtitle
    
    //퐐뤄버튼
    followButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-10-80, 3, 80, 24)];
    [followButton addTarget:self action:@selector(followButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    followButton.layer.cornerRadius = 5.0f;
    [self.subTitleView addSubview:followButton];
    
    followIcon = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 12, 24)];
    [followButton addSubview:followIcon];
    
    followBtnLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    followBtnLabel.font = [UIFont boldSystemFontOfSize:10];
    followBtnLabel.backgroundColor = [UIColor clearColor];
    [followButton addSubview:followBtnLabel];
    
    [self followerBtnSelect:NO];
    
    //공유버튼
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(followButton.frame.origin.x-5-followButton.frame.size.width, 3, 80, 24)];
    [shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    shareButton.backgroundColor = ColorFromRGB(0x49a1d9);
    shareButton.layer.cornerRadius = 5.0f;
    [self.subTitleView addSubview:shareButton];
    
    UIImageView *shareIcon = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 12, 24)];
    shareIcon.image = [UIImage imageNamed:@"icon_share"];
    [shareButton addSubview:shareIcon];
    
    UILabel *shareButtonTitle = [[UILabel alloc] initWithFrame:CGRectMake(shareIcon.frame.origin.x+shareIcon.frame.size.width,
                                                                          0,
                                                                          shareButton.frame.size.width-shareIcon.frame.origin.x-shareIcon.frame.size.width,
                                                                          shareButton.frame.size.height)];
    shareButtonTitle.backgroundColor = [UIColor clearColor];
    shareButtonTitle.textColor = ColorFromRGB(0xffffff);
    shareButtonTitle.text = NSLocalizedString(@"share", @"");
    shareButtonTitle.font = [UIFont boldSystemFontOfSize:11];
    shareButtonTitle.textAlignment = NSTextAlignmentCenter;
    [shareButton addSubview:shareButtonTitle];
    
    //테이블
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,self.bodyView.frame.size.width,self.bodyView.frame.size.height)];
    mTableView.dataSource = self;
    mTableView.delegate = self;
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.bodyView addSubview:mTableView];
}

-(void)followerBtnSelect:(BOOL)yn{

    if (yn) {
        followIcon.image = [UIImage imageNamed:@"icon_follow"];
        followIcon.frame = CGRectMake(10, 0, 12, 24);
        followBtnLabel.text = @"UnFollow";
        followBtnLabel.frame = CGRectMake(followIcon.frame.origin.x+followIcon.frame.size.width,
                                          0,
                                          80-followIcon.frame.origin.x-followIcon.frame.size.width,
                                          24);
        followBtnLabel.font = [UIFont systemFontOfSize:11];
        followButton.backgroundColor = ColorFromRGB(0x413c43);
        followBtnLabel.textColor = ColorFromRGB(0x615c65);
        followBtnLabel.textAlignment = NSTextAlignmentCenter;
    }else{
        followIcon.image = [UIImage imageNamed:@"icon_unfollow"];
        followIcon.frame = CGRectMake(10, 0, 12, 24);
        followBtnLabel.text = @"Follow";
        followBtnLabel.frame = CGRectMake(followIcon.frame.origin.x+followIcon.frame.size.width,
                                          0,
                                          80-followIcon.frame.origin.x-followIcon.frame.size.width,
                                          24);
        followBtnLabel.textAlignment = NSTextAlignmentCenter;
        followBtnLabel.font = [UIFont systemFontOfSize:11];
        followButton.backgroundColor = ColorFromRGB(0x49a1d9);
        followBtnLabel.textColor = ColorFromRGB(0xffffff);
    }
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark - 뒤로
-(void)backButtonAction:(id)sender{
    
    [appDelegate removeActivity];
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController removeStarView];
}

#pragma mark - 팔로우
-(void)followButtonAction:(id)sender{
    
    if (!duringNetwork) {
        
        UIButton *button = (UIButton*)sender;
        
        if (!button.selected) {
            [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Follow];
        }
        [self requestUnFollow:button.selected andStarID:self.starID];
    }
}

#pragma mark - 공유
-(void)shareButtonAction:(id)sender{
    
    [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Star_Share];
    [self makeActionSheetTitle:@"sns share"];
}

-(void)makeActionSheetTitle:(NSString*)title{
    
    NSString *fbTitle = enableFacebook ? @"Facebook" : @"Facebook Login";
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Kakao Talk",@"Kakao Story",fbTitle,@"Twitter", nil];
    [actionSheet showInView:self];
}

#pragma mark UIAction Sheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (buttonIndex) {
        case 0:
            //카카오톡
            [self goKakaoTalk];
            break;
            
        case 1:
            //카카오스토리
            [self goKakaoStory];
            break;
            
        case 2:
            //페북
            [self goFaceBook];
            break;
        case 3:
            //트위터
            [self goTwitter];
            break;
            
        default:
            break;
    }
}

#pragma mark 공유할내용


-(BOOL)applicationCanOpenURL:(NSString*)urlString{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]];
}

//공유할내용
-(NSString*)shareOfIssueTitle{
    return [[self.itemArray objectAtIndex:0] objectForKey:@"title"];
}

-(NSString*)shareOfIssueCaption{
    NSString *caption = [[self.itemArray objectAtIndex:0] objectForKey:@"caption"];
    return [appDelegate stringByHTMLEncodingWithString:caption];
}

-(NSString*)shareOfNewsURL{
    
    NSString *string = [[self.itemArray objectAtIndex:0] objectForKey:@"issue_id"];
    string = [NSString stringWithFormat:@"http://dispatch.appvista.com/news/?is=%@",string];
    return string;
}


-(NSString*)shareSchemeOpen{
    
    
    NSString *string = [[self.itemArray objectAtIndex:0] objectForKey:@"star_id"];
    
    //dispatch://launch?sid=6808&c=i
    string = [NSString stringWithFormat:@"dispatch://launch?sid=%@&c=s",string];
    return string;
}


#pragma mark 카카오톡
-(void)goKakaoTalk{
    if ([KakaoLinkCenter canOpenKakaoLink]) {
        
        
        NSMutableArray *metaInfoArray = [NSMutableArray array];
        
        NSDictionary *metaInfoAndroid = [NSDictionary dictionaryWithObjectsAndKeys:
                                         @"android", @"os",
                                         @"phone", @"devicetype",
                                         androidURL, @"installurl",
                                         [self shareSchemeOpen], @"executeurl",
                                         nil];
        
        NSDictionary *metaInfoIOS = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"ios", @"os",
                                     @"phone", @"devicetype",
                                     ituneURL, @"installurl",
                                     [self shareSchemeOpen], @"executeurl",
                                     nil];
        
        [metaInfoArray addObject:metaInfoAndroid];
        [metaInfoArray addObject:metaInfoIOS];
        
        [KakaoLinkCenter openKakaoAppLinkWithMessage:[NSString stringWithFormat:@"%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption]]
                                                 URL:[self shareOfNewsURL]
                                         appBundleID:[[NSBundle mainBundle] bundleIdentifier]
                                          appVersion:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
                                             appName:@"Dispatch"
                                       metaInfoArray:metaInfoArray];
    }else{
        //설치 안되어있음
    }
}

#pragma mark 카카오스토리
-(void)goKakaoStory{
    if ([KakaoLinkCenter canOpenStoryLink]) {
        
        
        [KakaoLinkCenter openStoryLinkWithPost:[NSString stringWithFormat:@"%@\n%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption],[self shareOfNewsURL]]
                                   appBundleID:[[NSBundle mainBundle] bundleIdentifier]
                                    appVersion:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
                                       appName:@"Dispatch"
                                       urlInfo:nil];
    }else{
        //설치 안되어있음
    }
}

#pragma mark 페이스북

-(void)goFaceBook{
    
    
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        
        NSString *text = [NSString stringWithFormat:@"%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption]];
        
        SLComposeViewController *facebook = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        [facebook setInitialText:text];
        [facebook addURL:[NSURL URLWithString:[self shareOfNewsURL]]];
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController presentViewController:facebook animated:YES completion:nil];
        
    }else{
        
        NSURL *urlToShare = [NSURL URLWithString:[self shareOfNewsURL]];
        
        FBShareDialogParams *shareParams = [[FBShareDialogParams alloc] init];
        shareParams.link = urlToShare;
        shareParams.name = [self shareOfIssueTitle];
        shareParams.description = [self shareOfIssueCaption];
        
        // If the Facebook app is installed and we can present the share dialog
        if ([FBDialogs canPresentShareDialogWithParams:shareParams]) {
            // Present the share dialog
            [FBDialogs presentShareDialogWithLink:shareParams.link
                                             name:shareParams.name
                                          caption:shareParams.caption
                                      description:shareParams.description
                                          picture:shareParams.picture
                                      clientState:nil
                                          handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                              if(error) {
                                                  // An error occurred, we need to handle the error
                                                  // See: https://developers.facebook.com/docs/ios/errors
                                              } else {
                                                  // Success
                                                  NSLog(@"result %@", results);
                                              }
                                          }];
            
        } else {
            
            // Prepare the web dialog parameters
            NSDictionary *feedParams = @{
                                         @"name" : shareParams.name,
                                         @"link" : shareParams.link
                                         };
            
            // Invoke the dialog
            [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                                   parameters:feedParams
                                                      handler:
             ^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                 if (error) {
                     NSLog(@"Error publishing story.");
                 } else {
                     if (result == FBWebDialogResultDialogNotCompleted) {
                         NSLog(@"User canceled story publishing.");
                     } else {
                         NSLog(@"Story published.");
                     }
                 }}];
        }
    }
}

#pragma mark 트위터
-(void)goTwitter{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    mTwitter = [[TWTweetComposeViewController alloc] init];
    
    
    
    NSString *text = [NSString stringWithFormat:@"%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption]];
    if (text.length > 100) {
        text = [text substringToIndex:100];
        text = [text stringByAppendingString:@"..."];
    }
    
    
    [mTwitter setInitialText:text];
    [mTwitter addURL:[NSURL URLWithString:[self shareOfNewsURL]]];
    [viewController presentModalViewController:mTwitter animated:YES];
    
    mTwitter.completionHandler = ^(TWTweetComposeViewControllerResult result){
        
        [self.mTwitter dismissModalViewControllerAnimated:YES];
        switch (result) {
            case SLComposeViewControllerResultCancelled:
                
                break;
            case SLComposeViewControllerResultDone:
                break;
                
            default:
                break;
        }
        
    };
}



#pragma mark - 사진선택
-(void)listLeftButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewControllerWithIndex:button.tag];
}

-(void)listRightButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewControllerWithIndex:button.tag];
}

-(void)appearPhotoViewControllerWithIndex:(NSInteger)index{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 6;
    photoController.adCount = appDelegate.starAdCount;
    photoController.mDelegate = self;
    photoController.currentImageIndex = index;
    photoController.imageURL = self.imageURL;
    photoController.analyticsAction = ANA_ACT_STAR;
    photoController.analyticsLabelDetail = ANA_LAB_Star_Photo;
    photoController.analyticsLabelWhole = ANA_LAB_Star_Photo_Whole;
    [photoController settingDataFromStar:self.itemArray];
    [viewController presentModalViewController:photoController animated:YES];
}

#pragma mark - 네트워크
-(void)requestStarInfoList{
    
    networkIndex = 1;
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&deviceid=%@&lang=%@&pagesize=100",self.starID,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
//    NSString *url = [NSString stringWithFormat:@"%@?id=%@&deviceid=%@&lang=%@",URL_STAR,self.starID,[[NSUserDefaults standardUserDefaults] objectForKey:@"uusks id"],appDelegate.currentLanguage];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_STAR,dataStr];
    [self requestURL:url];
}

-(void)requestStarInfoListWithPushID:(NSString*)pushID{
    
    networkIndex = 1;
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&deviceid=%@&lang=%@&route=pns&pid=%@&os=ios",self.starID,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],appDelegate.currentLanguage,pushID];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_STAR,dataStr];
    [self requestURL:url];
}

-(void)requestUnFollow:(BOOL)yn andStarID:(NSString*)_starID{
    
    
    networkIndex = 2;
    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&star_id=%@&follow=%d&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],_starID,yn?0:1,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
//    NSString *url = [NSString stringWithFormat:@"%@?deviceid=%@&starid=%@&follow=%d&lang=%@",URL_FOLLOW,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],_starID,yn?0:1,appDelegate.currentLanguage];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_FOLLOW,dataStr];
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"스타리스트 네트워크 요청 : %@",url);
            }
            
            [mTableView reloadData];
            
        }
    }
}


#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    [appDelegate removeActivity];
    duringNetwork = NO;
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"스타상세 : %@",resultDictionary);
    
    if (networkIndex == 1) {
        
        self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                
                resultDictionary = [resultDictionary objectForKey:@"data"];
                
                NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                self.titleLabel.text = ([appDelegate checkObject:[resultDictionary objectForKey:@"name"]]) ? [resultDictionary objectForKey:@"name"] : nil;
                NSString *follow = ([appDelegate checkObject:[resultDictionary objectForKey:@"follower"]]) ? [resultDictionary objectForKey:@"follower"] : @"0";
                self.subTitleLabel.text = [NSString stringWithFormat:@"%@ : %@",NSLocalizedString(@"follow", @""), follow];
                BOOL isFollow = ([appDelegate checkObject:[resultDictionary objectForKey:@"isfollow"]]) ? [[resultDictionary objectForKey:@"isfollow"] boolValue] : NO;
                followButton.selected = isFollow;
                [self followerBtnSelect:followButton.selected];
                
                if (items) {
                    [self.itemArray addObjectsFromArray:items];
                }
                
                [mTableView reloadData];
                
            }
        }
    }else if(networkIndex == 2){
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                //재대로 팔/언팔됨
                NSString *message = followButton.selected ?
                (languagesKorean ? @"Success\nUnfollow 하셨습니다.\n스타 페이지에서 Follow 하실 수 있습니다." : @"Success Unfollow this Star\nYou can Follow at Star page."):
                (languagesKorean ? @"Success\nFollow 하셨습니다.\n해당 스타 신규 기사를\n알람으로 알려드립니다." : @"Success Follow this Star\nYou can receive alarm of this star news");
                [appDelegate alertViewWithMessage:message andTimeInterval:2.0f];
                followButton.selected = !followButton.selected;
                [self followerBtnSelect:followButton.selected];
                
                //팔뤄 개신
                NSString *follow = ([appDelegate checkObject:[resultDictionary objectForKey:@"follower"]]) ? [resultDictionary objectForKey:@"follower"] : @"0";
                self.subTitleLabel.text = [NSString stringWithFormat:@"%@ : %@",NSLocalizedString(@"follow", @""), follow];
            }else if([[resultDictionary objectForKey:@"return_code"] intValue] == 1){
                //인원초과함
                NSString *string = NSLocalizedString(@"followlimit", @"");
                NSString *peoplenumber = [NSString stringWithFormat:@"%@",[resultDictionary objectForKey:@"msg"]];
                NSMutableString *message = [NSMutableString stringWithString:string];
                NSRange range = [message rangeOfString:@"00"];
                [message replaceCharactersInRange:range withString:peoplenumber];
                
                [appDelegate alertViewWithMessage:message andTimeInterval:2.0f];
            }
        }
    }
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    [appDelegate removeActivity];
    NSLog(@"스타 네트워크 요청 실패 : %@",error);
}

#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger numberOfRows = ([self.itemArray count]%2 == 0) ? (int)([self.itemArray count]/2) : (int)([self.itemArray count]/2)+1;
    return numberOfRows;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 146;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"RankingCell";
    ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self;
    }
    
    
    NSString *first, *second;
    NSString *firstURL, *secondURL;
    
    if ((indexPath.row*2) < [self.itemArray count]) {
        
        //재사용시 기존 이미지 가림
        if (!cell.leftImage.image || cell.leftImage.tag != indexPath.row) {
            cell.leftImage.image = nil;
        }
        
        first = [[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"title"];
        firstURL = [NSString stringWithFormat:@"%@%@",self.imageURL,[[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"]];
        cell.leftImage.tag = indexPath.row;
        cell.leftButton.tag = indexPath.row*2;
        [cell.leftButton addTarget:self action:@selector(listLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        /*
        [appDelegate loadAsyncImageFromURL:[NSURL URLWithString:firstURL] imageBlock:^(UIImage *image) {
            
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = image;
            }
            
        } errorBlock:^{
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = [UIImage imageNamed:@"thumb_290272"];
            }
        }];*/
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
            
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = image;
                [appDelegate effectFaceoutTargetView:cell.leftImage];
            }
        } errorBlock:^{
            
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = nil;
            }
        }];
    }
    if ((indexPath.row*2)+1 < [self.itemArray count]) {
        
        //재사용시 기존 이미지 가림
        if (!cell.rightImage.image || cell.rightImage.tag != indexPath.row) {
            cell.rightImage.image = nil;
        }
        
        second = [[self.itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"title"];
        secondURL = [NSString stringWithFormat:@"%@%@",self.imageURL,[[self.itemArray objectAtIndex:(indexPath.row*2)+1]objectForKey:@"thumb_url"]];
        cell.rightImage.tag = indexPath.row;
        cell.rightButton.tag = (indexPath.row*2)+1;
        [cell.rightButton addTarget:self action:@selector(listRightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        /*
        [appDelegate loadAsyncImageFromURL:[NSURL URLWithString:secondURL] imageBlock:^(UIImage *image) {
            
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = image;
            }
            
        } errorBlock:^{
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = [UIImage imageNamed:@"thumb_290272"];
            }
            NSLog(@"이슈리스트 오른쪽이미지 에러");
        }];*/
        
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[self.itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
            
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = image;
                [appDelegate effectFaceoutTargetView:cell.rightImage];
            }
            
        } errorBlock:^{
            
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = nil;
            }
        }];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell cellOfIssueWithHotList:nil andFirstTitle:first andSecondTitle:second];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    
    if (!duringNetwork) {
        
        if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
            //다음페이지로 이동
        }
    }
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:NO];
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
   
    if (!duringNetwork) {
        if (scrollView.contentOffset.y < -50) {
            //가장첫페이지
            
        }
    }
    
    if (!decelerate) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:YES];
}

@end
